package RoleService

import (
	"context"
	"errors"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/internal/service/BaseService"
	"seawolf-admin-go/utility/response"
	"time"
)

func Update(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	// 修改时间
	data["update_at"] = time.Now().Unix()
	// 增加附加数据
	if req.UpdateInsertData != nil {
		otherData := req.UpdateInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 删除更新时不需要的字段
	BaseService.DelIgnoreProperty(data, req.UpdateIgnoreProperty)
	// 编辑前方法
	if req.UpdateBeforeFn != nil {
		respRes := req.UpdateBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	err := g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		obj := tx.Model(req.TableName).Unscoped()
		res, err := obj.Fields(obj.GetFieldsStr()).Where("id", req.Id).Update(data)
		if err != nil {
			return err
		}
		changeRow, err := res.RowsAffected()
		if err != nil {
			return err
		}
		if changeRow < 1 {
			return errors.New("编辑失败")
		}
		// 删除原来的 sys_role_department
		_, err = tx.Model("sys_role_department").Where(
			"role_id", req.Id).Delete()
		if err != nil {
			return err
		}
		// 删除原来的 sys_role_menu
		_, err = tx.Model("sys_role_menu").Where(
			"role_id", req.Id).Delete()
		if err != nil {
			return err
		}

		menuIdList := r.Get("menuIdList").Array()
		// 插入 sys_role_department
		rmData := g.List{}
		for _, item := range menuIdList {
			rmData = append(rmData, g.Map{
				"role_id": req.Id,
				"menu_id": item,
			})
		}
		if len(rmData) > 0 {
			res, err = tx.Model("sys_role_menu").Insert(rmData)
			if err != nil {
				return err
			}
		}

		departmentIdList := r.Get("departmentIdList").Array()
		// 插入 sys_role_department
		rdData := g.List{}
		for _, item := range departmentIdList {
			rdData = append(rdData, g.Map{
				"role_id":       req.Id,
				"department_id": item,
			})
		}
		if len(rdData) > 0 {
			res, err = tx.Model("sys_role_department").Insert(rdData)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "编辑成功", g.Map{
		"id": req.Id,
	})
}
